package cn.net.shuxing.yifu.common.service;


import cn.net.shuxing.yifu.common.bean.SysUserRealInfo;
import cn.net.shuxing.yifu.common.bean.UserRealInfo;
import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.constant.OssConstant;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.mapper.SysUserRealInfoMapper;
import cn.net.shuxing.yifu.common.mapper.UserRealInfoMapper;
import cn.net.shuxing.yifu.common.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

@Service
public class SysUserRealInfoService extends BaseService<SysUserRealInfo, SysUserRealInfoMapper> {

    //    public String idCardNo;
//    public String realName;
    private String bucketName = OssConstant.ossBucketName;

    @Autowired
    private OssCommonService ossCommonService;

    public List<SysUserRealInfo> getsByRealName(String realName) {
        Map<String, Object> map = new HashMap<>();
        map.put("realName", realName);
        List<SysUserRealInfo> userRealInfos = this.gets(map);
        return userRealInfos;
    }

//    public UserRealInfo getByPhoneNum(String phoneNum) {
//        Integer userId = userInfoBindService.getByPhoneNum(phoneNum).getId();
//        return getByPrimaryKey(userId);
//    }

    public SysUserRealInfo getByIdCardNum(String idCardNum) {
        SysUserRealInfo userRealInfo = new SysUserRealInfo();
        userRealInfo.clearCreateTimeAndUpdateTime();
        userRealInfo.setIdCardNum(idCardNum);
        return get(userRealInfo);
    }

    /**
     * 身份证实名认证
     */
    public boolean verify(String idCardNo, String realName) {
        String host = "http://vipidcardcheck.haoservice.com";
        String path = "/idcard/VerifyIdcardv2";
        String method = "GET";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("cardNo", idCardNo);
        querys.put("realName", realName);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
//            获取response的body
            String responseStr = EntityUtils.toString(response.getEntity());
            JSONObject responseJson = (JSONObject) JSON.parse(responseStr);
            Object error_code = responseJson.get("error_code");
            return error_code.equals(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


//    /**
//     * return
//     *
//     * @param args
//     */
//    public static void main(String[] args) {
//        UserRealInfoService userRealInfoService = new UserRealInfoService();
//        boolean verify = userRealInfoService.verify(UserRealInfoService.idCardNo, UserRealInfoService.realName);
//        System.out.println(verify);
//    }

    /*
     * 获取参数的json对象
     */
    public JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 验证身份证照片
     *
     * @param idCardPhoto
     * @param isFace
     * @param userRealInfo
     * @return
     */
    public BaseDto verifyIdCardPhoto(File idCardPhoto, boolean isFace, UserRealInfo userRealInfo) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", isFace ? "face" : "back");
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //            String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
        String imgBase64 = "";
        try {

            byte[] content = new byte[(int) idCardPhoto.length()];
            FileInputStream finputstream = new FileInputStream(idCardPhoto);
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
        } catch (IOException e) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg(e.getMessage());
            return baseDto;
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", imgBase64);
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("Http code", stat);
                resultMap.put("http header error msg", response.getFirstHeader("X-Ca-Error-Message"));
                resultMap.put("Http body error msg", EntityUtils.toString(response.getEntity()));

                BaseDto baseDto = new BaseDto();
                baseDto.setCode(CodeConst.ERROR);
                baseDto.setMsg(JSON.toJSONString(resultMap));
                return baseDto;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            if (is_old_format) {
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject out = JSON.parseObject(output);
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(out.get("num")) && userRealInfo.getRealName().equals(out.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (out.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }

            } else {
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(res_obj.get("num")) && userRealInfo.getRealName().equals(res_obj.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (res_obj.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(idCardPhoto, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public BaseDto verifyIdCardPhoto(InputStream idCardPhoto, String suffix, Integer size, boolean isFace, UserRealInfo userRealInfo) {
        String host = "http://dm-51.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_idcard.json";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Boolean is_old_format = false;//如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", isFace ? "face" : "back");
        String config_str = configObj.toString();
        //            configObj.put("min_size", 5);
        //            String config_str = "";

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
        String imgBase64 = "";
        byte[] content = new byte[size];
        try {


            InputStream finputstream = idCardPhoto;
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
        } catch (IOException e) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg(e.getMessage());
            return baseDto;
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", imgBase64);
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != 200) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("Http code", stat);
                resultMap.put("http header error msg", response.getFirstHeader("X-Ca-Error-Message"));
                resultMap.put("Http body error msg", EntityUtils.toString(response.getEntity()));

                BaseDto baseDto = new BaseDto();
                baseDto.setCode(CodeConst.ERROR);
                baseDto.setMsg(JSON.toJSONString(resultMap));
                return baseDto;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            if (is_old_format) {
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject out = JSON.parseObject(output);
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(out.get("num")) && userRealInfo.getRealName().equals(out.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (out.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }

            } else {
                if (isFace) {
                    if (userRealInfo.getIdCardNum().equals(res_obj.get("num")) && userRealInfo.getRealName().equals(res_obj.get("name"))) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                        return baseDto;
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("身份证照片和真实信息不符");
                        return baseDto;
                    }
                } else {
                    if (res_obj.get("success").equals(true)) {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setData("验证通过");
                        uploadIdCardPhoto(content, suffix, isFace, userRealInfo.getId());
                    } else {
                        BaseDto baseDto = new BaseDto();
                        baseDto.setCode(CodeConst.ERROR);
                        baseDto.setMsg("上传的身份证背面照片不是身份证背面照片");
                        return baseDto;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传身份证照片
     *
     * @param idCardPhoto
     * @param isFace
     * @param userId
     * @return
     */
    public BaseDto uploadIdCardPhoto(File idCardPhoto, boolean isFace, Integer userId) {
        String bucketName = OssConstant.ossBucketName;
        String fileName = idCardPhoto.getName();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if (!suffix.startsWith(".")) {
            suffix += ".";
        }
        String objectName = "userInfo" + userId + "idCard" + (isFace ? "Face" : "Back") + "Photo" + suffix;

        if (!ossCommonService.uploadFile(bucketName, objectName, idCardPhoto)) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg(objectName + "文件上传失败");
            return baseDto;
        }

        /** 存入数据库 **/
        SysUserRealInfo userRealInfo = getByPrimaryKey(userId);
        if (isFace) {
            userRealInfo.setIdCardFrontPhoto(bucketName + "/" + objectName);
        } else {
            userRealInfo.setIdCardBackPhoto(bucketName + "/" + objectName);
        }
        update(userRealInfo);

        BaseDto baseDto = new BaseDto();
        baseDto.setData(objectName + "上传完成");
        return baseDto;
    }

    /**
     * 上传身份证照片
     *
     * @param content
     * @param suffix
     * @param isFace
     * @param userId
     * @return
     */
    public BaseDto uploadIdCardPhoto(byte[] content, String suffix, boolean isFace, Integer userId) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAIQb8xLiRdju3q";
        String accessKeySecret = "1G6AFqff9UyONRy8zroKpu8UZjfnZj";
        String bucketName = OssConstant.ossBucketName;
        if (!suffix.startsWith(".")) {
            suffix += ".";
        }
        String objectName = "userInfo-" + userId + "-idCard" + (isFace ? "Face" : "Back") + "Photo" + suffix;


        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        if (!ossCommonService.uploadFile(bucketName, objectName, content, suffix)) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("文件写入错误");
        }

        if (isFace) {
            SysUserRealInfo userRealInfo = getByPrimaryKey(userId);
            if (isFace) {
                userRealInfo.setIdCardFrontPhoto(objectName);
            } else {
                userRealInfo.setIdCardBackPhoto(objectName);
            }
        }
        BaseDto baseDto = new BaseDto();
        baseDto.setData(objectName + "上传完成");
        return baseDto;
    }

    /**
     * 上传手持身份证照片
     *
     * @param content
     * @param suffix
     * @param userId
     * @return
     */
    public BaseDto uploadTakingCardPhoto(byte[] content, String suffix, Integer userId) {

        if (!suffix.startsWith(".")) {
            suffix += ".";
        }
        String objectName = "userInfo" + userId + "takingCard" + "Photo" + suffix;

        // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        if (!ossCommonService.uploadFile(bucketName, objectName, content, suffix)) {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("文件写入错误");
        }

        /** 存入数据库 **/
        SysUserRealInfo userRealInfo = getByPrimaryKey(userId);
        userRealInfo.setTakingCardPhoto(bucketName + "/" + objectName);
        update(userRealInfo);
        BaseDto baseDto = new BaseDto();
        baseDto.setData(objectName + "上传完成");
        return baseDto;
    }

    /**
     * 获取照片
     *
     * @param userId
     * @return
     */
    public SysUserRealInfo getPhotosByUserId(Integer userId) {
        SysUserRealInfo userRealInfo = getByPrimaryKey(userId);
        userRealInfo.setIdCardFrontPhotoUrl(getUrl(userRealInfo.getIdCardFrontPhoto()));
        userRealInfo.setTakingCardPhotoUrl(getUrl(userRealInfo.getTakingCardPhoto()));
        return userRealInfo;
    }

    public String getUrl(String path) {
        String[] split = path.split("/");
        String bukketName = split[0];
        String objectName = split[1];
        return ossCommonService.getUrl(bucketName, objectName);
    }

    public byte[] getFileContent(String path) {
        String[] split = path.split("/");
        String bukketName = split[0];
        String objectName = split[1];
        return ossCommonService.getFileContent(bucketName, objectName);
    }

//    public Integer getUserIdByPhoneNumAndIdCard(String phoneNum, String IdCardNum){
//        Integer userId = 0 ;
//        if (phoneNum!=null){
//            userId = userInfoBindService.getByPhoneNum(phoneNum).getId();
//        }if (IdCardNum != null){
//            UserRealInfo userRealInfo = new UserRealInfo();
//            userRealInfo.clearCreateTimeAndUpdateTime();
//            userRealInfo.setIdCardNum(IdCardNum);
//            userId = get(userRealInfo).getId();
//        }
//        return userId;
//    }


}